import { Breadcrumb, Button, Space, Tag, Descriptions, Divider, Table, Modal, Spin, message, Form, Input, Select } from 'antd'
import { useParams } from '@/router/hooks'
import { Link, useNavigate } from 'react-router-dom'
import { useEffect, useState } from 'react'
import { serviceDeleteId, serviceFlowControl, getServiceCatalogDetail, servicePatch } from '@/api/sharing/serviceCatalog'
import styled from 'styled-components'
import BlackWhiteList from './modules/BlackWhiteList'

/* 流量控制弹窗 */
const LimitCountModal = ({ isFormOpen, setIsFormOpen }) => {
  const [form] = Form.useForm()

  /* 流量控制 */
  const handleOk = () => {
    const values = form.getFieldsValue()
    serviceFlowControl(values)
      .then((response) => {
        if (response.code === 200) {
          setIsFormOpen(false)
          message.success('流量控制成功')
          form.resetFields()
        } else {
          message.error('操作失败')
        }
      })
      .catch((error) => {
        console.log('error', error)
      })
  }
  const handleCancel = () => {
    setIsFormOpen(false)
  }
  return (
    <Modal title="流量控制" open={isFormOpen} onOk={handleOk} onCancel={handleCancel}>
      <Form layout="inline" form={form} initialValues={{ type: 'SECONDS', times: '' }}>
        <Form.Item label="服务流量控制" name="type">
          <Select
            style={{ width: '100px' }}
            placeholder="请选择"
            options={[
              { label: '每秒', value: 'SECONDS' },
              { label: '每分钟', value: 'MINUTES' },
              { label: '每小时', value: 'HOURS' },
              { label: '每天', value: 'DAYS' },
            ]}
          />
        </Form.Item>
        <Form.Item
          name="times"
          rules={[
            {
              pattern: /^\d+$/,
              message: '请填入整数字',
            },
          ]}
        >
          <Input placeholder="请填入整数字" />
        </Form.Item>
      </Form>
    </Modal>
  )
}

const ServiceCatalogDetail = () => {
  const { id } = useParams()
  const [fullData, setFullData] = useState({})
  const [loading, setLoading] = useState(true)
  const [isFormOpen, setIsFormOpen] = useState(false)
  const [isModalOpen, setIsModalOpen] = useState(false)
  const navigate = useNavigate()
  const confirm = Modal.confirm

  useEffect(() => {
    getServiceCatalogDetail(id)
      .then((response) => {
        setFullData(response.data)
      })
      .finally(() => {
        setLoading(false) // 请求完成后关闭 loading
      })
  }, [])
  const options = [
    { label: '每秒', value: 'SECONDS' },
    { label: '每分钟', value: 'MINUTES' },
    { label: '每小时', value: 'HOURS' },
    { label: '每天', value: 'DAYS' },
  ]
  /* 删除操作 */
  const handleDeleteRow = () => {
    const id = fullData.id
    confirm({
      title: '确认删除数据?',
      icon: <ExclamationCircleFilled />,
      autoFocusButton: null,
      onOk() {
        return serviceDeleteId(id).then((res) => {
          message.success('删除成功')
          navigate('/integration/sharing/serviceCatalog')
        })
      },
      onCancel() {},
    })
  }

  /* 发布/下线操作*/
  const handlePublish = (row) => {
    confirm({
      title: row.status == '1' ? '下线API服务' : '发布API服务',
      autoFocusButton: null,
      content: (
        <p>
          API服务发布注册后才可被其他服务或用户访问，进行API编排，确定将<Button type="link">“{row.name}”</Button>服务{row.status == '1' ? '下线' : '发布'}吗？
        </p>
      ),
      onOk() {
        setLoading(true)
        const status = row.status == '1' ? '0' : '1'
        return servicePatch({ id: row.id, status }).then((res) => {
          getServiceCatalogDetail(id)
            .then((response) => {
              setFullData(response.data)
              message.success(row.status == '1' ? '下线成功' : '发布成功')
            })
            .finally(() => {
              setLoading(false) // 请求完成后关闭 loading
            })
        })
      },
      onCancel() {},
    })
  }

  return (
    <StyleWrap>
      <Spin spinning={loading} tip="Loading...">
        <div className="page-breadcrumb">
          <Breadcrumb
            items={[
              {
                title: <Link to="/integration/sharing/serviceCatalog">服务目录</Link>,
              },
              {
                title: '目录详情-设施信息服务(数据接口)',
              },
            ]}
          />
          <Space>
            <Button onClick={() => handlePublish(fullData)}>{fullData.status == '0' ? '发布服务' : '下线服务'}</Button>
            <Button disabled={fullData.status == '1'} onClick={() => navigate(`/integration/sharing/serviceCatalog/${id}/edit`)}>
              编辑服务
            </Button>
            <Button disabled={fullData.status == '1'} onClick={() => navigate('/integration/sharing/serviceCatalog/1869301007282225154/tryout')}>
              服务测试
            </Button>
            <Button disabled={fullData.status == '1'} onClick={() => setIsFormOpen(true)}>
              流量控制
            </Button>
            <Button
              disabled={fullData.status == '1'}
              onClick={() => {
                setIsModalOpen(true)
              }}
            >
              服务授权
            </Button>
            <Button danger onClick={handleDeleteRow}>
              删 除
            </Button>
          </Space>
        </div>
        <Descriptions title="基本信息" column={4}>
          <Descriptions.Item label="服务名称">{fullData.name}</Descriptions.Item>
          <Descriptions.Item label="服务标签">{fullData.labels && Object.keys(fullData.labels)?.map((key) => <Tag key={key}>{`${key}: ${fullData.labels[key]}`}</Tag>)}</Descriptions.Item>
          <Descriptions.Item label="服务状态">
            <Tag>{fullData.status == '0' ? '未发布' : '已发布'}</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="创建时间">{fullData.createTime}</Descriptions.Item>
          <Descriptions.Item label="服务路径">{fullData.uri}</Descriptions.Item>
          <Descriptions.Item label="服务描述" span={3}>
            {fullData?.desc}
          </Descriptions.Item>
        </Descriptions>
        <Divider />
        <Descriptions title="API请求" column={4}>
          <Descriptions.Item label="请求协议">
            <Tag>{fullData?.apiRequestVo?.requestProtocol == '0' ? 'HTTP' : 'HTTPS'}</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="请求Path">{fullData.apiRequestVo?.requestPath}</Descriptions.Item>
          <Descriptions.Item label="Method">
            <Tag>{fullData.apiRequestVo?.method}</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="智能路由">{fullData.apiRequestVo?.autoRoute}</Descriptions.Item>
        </Descriptions>
        <Table
          style={{ marginTop: '20px' }}
          bordered
          columns={[
            {
              title: '入参定义',
              align: 'left',
              children: [
                {
                  title: '参数名称',
                  dataIndex: 'name',
                },
                {
                  title: '参数位置',
                  dataIndex: 'location',
                },
                {
                  title: '必填',
                  dataIndex: 'necessary',
                  render: (text) => {
                    return text === true ? '是' : '否'
                  },
                },
                {
                  title: '默认值',
                  dataIndex: 'defaultValue',
                },
                // {
                //     title: '映射',
                //     dataIndex: 'mapping',
                //     render: (text) => {
                //         return text === true ? '是' : '否'
                //     },
                // },
              ],
            },
          ]}
          dataSource={fullData.apiRequestVo?.requestParams || []}
        ></Table>
        <Divider />
        <Descriptions title="后端服务" column={4}>
          <Descriptions.Item label="请求协议">
            <Tag>{fullData?.apiRequestVo?.apiBacServiceVo == '0' ? 'HTTP' : 'HTTPS'}</Tag>
          </Descriptions.Item>
          {/* <Descriptions.Item label="请求方式">{fullData.apiBacServiceVo?.method}</Descriptions.Item> */}
          <Descriptions.Item label="超时（ms）">{fullData.apiBacServiceVo?.overTime}</Descriptions.Item>
          <Descriptions.Item label="服务地址">{fullData.apiBacServiceVo?.serviceAddress}</Descriptions.Item>
          {/* <Descriptions.Item label="请求Path">/cs052403_20000/*</Descriptions.Item> */}
        </Descriptions>
        {/* <Table
                    style={{ marginTop: '20px' }}
                    bordered
                    columns={[
                        {
                            title: '后端服务参数',
                            align: 'left',
                            children: [
                                {
                                    title: '参数名称',
                                    dataIndex: 'name',
                                },
                                {
                                    title: '参数位置',
                                    dataIndex: 'location',
                                },
                                {
                                    title: '必填',
                                    dataIndex: 'necessary',
                                    render: (text) => {
                                        return text === true ? '是' : '否'
                                    },
                                },
                                {
                                    title: '默认值',
                                    dataIndex: 'defaultValue',
                                },
                                {
                                    title: '映射',
                                    dataIndex: 'mapping',
                                    render: (text) => {
                                        return text === true ? '是' : '否'
                                    },
                                },
                            ],
                        },
                    ]}
                    dataSource={fullData.apiBacServiceVo?.serviceParams || []}
                ></Table> */}
      </Spin>
      {/* 黑白名单弹窗 */}
      <BlackWhiteList isModalOpen={isModalOpen} setIsModalOpen={setIsModalOpen} id={id} />
      {/* 流量控制弹窗 */}
      <LimitCountModal isFormOpen={isFormOpen} setIsFormOpen={setIsFormOpen} />
    </StyleWrap>
  )
}

const StyleWrap = styled.div`
  padding: 16px;
`
export default ServiceCatalogDetail
